// <copyright file="Driver.cs" company="Bill Fellows">
// Copyright (c) Blabla. All rights reserved.
// </copyright>
namespace SSISDeploy.Console
{
    using System.IO;
    using System.Xml;
    using SSISDeploy.Components;

    /// <summary>
    /// The driver for the deploy application
    /// </summary>
    public class Driver
    {
        /// <summary>
        /// The main hook for this application
        /// </summary>
        /// <param name="args">command line arguments for the program</param>
        public static void Main(string[] args)
        {
            // Simpy attempt to call the deploy utility
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string parentFolder = string.Empty;
            string newFolder = string.Empty;
            string manifest = @"C:\sandbox\SSISPatterns\SSISPatterns\bin\Deployment\SSISPatterns.SSISDeploymentManifest";

            server = "localhost";
            parentFolder = @"\\";
            newFolder = "bfellows";

            // deploy.GetDirectory(server, parentFolder);
            bool fullTest = false;
            if (fullTest)
            {
                CreateRecursiveFolders();
                DeleteFolders();
                UploadFile();
                DeleteFile();
                PackageExists();
                parentFolder = @"recursive0";
                deploy.DeleteFolderRecursive(server, parentFolder);
            }

            // CreateRecursiveFolders();
            // UploadFile();
            // deploy.Enumerate(server, parentFolder);
            // System.Console.Read();
            // DtUtilWrapper foo = new DtUtilWrapper();
            // foo.DeleteFolderRecursive(server, @"\\");
            parentFolder = "\\recursiveA\\recursiveB\\recursiveC\\recursiveD\\recursiveE\\recursiveF";
            CommandLineCall(args);

            // deploy.CreateFolder(server, "\\recursive0", "recursiveB");
            // System.IO.DirectoryInfo di = null;
            // di = System.IO.Directory.GetParent(@"C:\");
            // System.Console.WriteLine(deploy.GetParentPath("\\recursive0\\recursive1\\recursive2\\recursive3\\recursive4\\recursive5"));
            // System.Console.WriteLine(deploy.GetParentPath(deploy.GetParentPath("\\recursive0")));
            // System.Console.Read();
            // deploy.CreateFolder(server, "\\recursive0\\recursive1\\recursive2\\recursive3\\recursive4\\recursive5", "recursive6");
            // deploy.DeployManifest(server, parentFolder, manifest);
            // Manifest();
            // System.Console.Read();
            // deploy.CreateFolder(server, parentFolder, newFolder);

            // deploy.CreateFolder(server, newFolder, "Subfolder25");
        }

        /// <summary>
        /// Initial test method for deploying a manifest.  Ready for deletion
        /// </summary>
        public static void Manifest()
        {
            string fileName = @"C:\sandbox\SSISPatterns\SSISPatterns\bin\Deployment\SSISPatterns.SSISDeploymentManifest";
            FileStream fs = File.Open(fileName, FileMode.Open); 
            XmlTextReader reader = new XmlTextReader(fs);

            System.Collections.Generic.List<string> packages = null;
            packages = new System.Collections.Generic.List<string>();
            string baseFolderOnDisk = string.Empty;
            baseFolderOnDisk = "";
            System.IO.DirectoryInfo dir = null;
            dir = System.IO.Directory.GetParent(fileName);
            baseFolderOnDisk = dir.ToString();

            // <Package>HelloWorld.dtsx</Package></DTSDeploymentManifest>
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (string.Equals(reader.Name, "package", System.StringComparison.CurrentCultureIgnoreCase))
                    {
                        packages.Add(reader.ReadElementContentAsString());
                    }
                }
            }

            // at this point we know all the files and where they should exist.
            // Assume they've also passed in the sql server folder, default of \

            // 1)  If the folder/path exists, purge it and any sub-entries
            // 2)  Create the folder/path if it does not exist
            // 3)  Iterate through the items from the manifest
            //     Verify they exist on disk and attempt to store to sql server
            // 4)  Print out a listing of everything deleted
            //     Print out as listing of everything created (grab versions for packages)
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();
            string server = string.Empty;
            server = "localhost";
            deploy.FolderExists(server, "");
        }

        /// <summary>
        /// Not even worthy to lick the boots of GetOpt but for the time being, it will suffice for 
        /// grabbing command line arguments.
        /// </summary>
        /// <param name="args">An array of arguments to control the utility</param>
        public static void CommandLineCall(string[] args)
        {
            // validate the options
            // short term hack to make a prototype release
            // Expected argument list looks like
            // -server "server name"
            // -manifest "C:\SSISProject\MyProject\bin\Deployment\MyProject.SSISDeploymentManifest"
            // -path "\Foo\bar"
            // [-simulateOnly]
            bool hasServerName = false;
            bool hasManifest = false;
            bool hasPath = false;
            bool simulateOnly = false;

            string server = string.Empty;
            string manifest = string.Empty;
            string path = string.Empty;
            string argument = string.Empty;

            System.Collections.Generic.Dictionary<string, string> parameters = null;
            parameters = new System.Collections.Generic.Dictionary<string, string>();

            for (int index = 0; index < args.Length; index++)
            {
                argument = args[index];

                if (string.Compare(argument, "-server", true) == 0)
                {
                    if (args.Length > index + 1)
                    {
                        server = args[index + 1];
                        hasServerName = true;
                    }
                }

                if (string.Compare(argument, "-manifest", true) == 0)
                {
                    if (args.Length > index + 1)
                    {
                        manifest = args[index + 1];
                        hasManifest = true;
                    }
                }

                if (string.Compare(argument, "-path", true) == 0)
                {
                    if (args.Length > index + 1)
                    {
                        path = args[index + 1];
                        hasPath = true;
                    }
                }

                if (string.Compare(argument, "-simulateonly", true) == 0)
                {
                    simulateOnly = true;
                }
            }

            // If everything is set except for the path, we'll assign a dummy value of \
            // Strike that, if we did that, we'd nuke everything in their root folder which 
            // wouldn't be a great way to instill confidence
            if (hasManifest && hasPath && hasServerName)
            {
                // System.Console.WriteLine(string.Format("server:  {0}  manifest: {1}  path:  {2}", server, manifest, path));
                SSISConsoleDeploy deploy = null;
                deploy = new SSISConsoleDeploy();
                deploy.DeployManifest(server, path, manifest, simulateOnly);
            }
            else
            {
                string usage = 
@"Deploys an SSIS manifest to a folder within SQL Server.
This will remove all the existing content in the selected folder so 
 use caution if you are passing in the root folder \ 
The simulateOnly parameter will generate all the statements that would
be executed but make no actual changes to the database.

SSISDeploy.Console.exe
    -server ""serverName"" 
    -manifest ""C:\SSISProject\MyProject\MyProject.SSISDeploymentManifest"" 
    -path ""\foo\bar"" 
    [-simuateOnly]
";
                System.Console.WriteLine(usage);
            }
        }

        /// <summary>
        /// Initial test method.  Ready for deletion
        /// </summary>
        public static void PackageExists()
        {
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string packagePathAndName = string.Empty;
            server = "localhost";
            packagePathAndName = @"\bfellows\Subfolder25\HelloWorld";
            System.Console.WriteLine(deploy.FolderExists(server, packagePathAndName));
            packagePathAndName = @"\bfellows\Subfolder25\HelloWorldDNE";
            System.Console.WriteLine(deploy.FolderExists(server, packagePathAndName));
            System.Console.Read();
        }

        /// <summary>
        /// Initial test method.  Ready for deletion
        /// </summary>
        public static void UploadFile()
        {
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string packagePathAndName = string.Empty;
            string pathToDtsx = string.Empty;

            server = "localhost";
            packagePathAndName = @"\bfellows\Subfolder25\HelloWorld";
            pathToDtsx = @"..\..\HelloWorld.dtsx";
            packagePathAndName = "recursive0\\recursive1\\recursive2\\recursive3\\recursive4\\Hello5";

            deploy.CopyPackage(server, pathToDtsx, packagePathAndName);
            System.Console.Read();
        }

        /// <summary>
        /// Initial test method.  Ready for deletion
        /// </summary>
        public static void DeleteFile()
        {
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string parentFolder = string.Empty;
            string newFolder = string.Empty;

            server = "localhost";
            parentFolder = @"\bfellows\Subfolder25";
            newFolder = "HelloWorld";

            deploy.DeletePackage(server, parentFolder, newFolder);
            System.Console.Read();
        }

        /// <summary>
        /// Initial test method.  Ready for deletion
        /// </summary>
        public static void CreateRecursiveFolders()
        {
            // Need to pull in nunit fairly soon to get this into a better state

            // Simpy attempt to call the deploy utility
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string parentFolder = string.Empty;
            string newFolder = string.Empty;

            server = "localhost";
            parentFolder = "\\";
            newFolder = "recursive{0}";
            deploy.CreateFolder(server, "\\", "recursive0");
            deploy.CreateFolder(server, "recursive0", "recursive1");
            deploy.CreateFolder(server, "recursive0\\recursive1", "recursive2");
            deploy.CreateFolder(server, "recursive0\\recursive1\\recursive2", "recursive3");
            deploy.CreateFolder(server, "recursive0\\recursive1\\recursive2\\recursive3", "recursive4");
            deploy.CreateFolder(server, "recursive0\\recursive1\\recursive2\\recursive3\\recursive4", "recursive5");
            deploy.CreateFolder(server, "recursive0\\recursive1\\recursive2\\recursive3\\recursive4\\recursive5", "recursive6");
            System.Console.Read();
        }

        /// <summary>
        /// Initial test method.  Ready for deletion
        /// </summary>
        public static void DeleteFolders()
        {
            // Need to pull in nunit fairly soon to get this into a better state

            // Simpy attempt to call the deploy utility
            SSISConsoleDeploy deploy = null;
            deploy = new SSISConsoleDeploy();

            string server = string.Empty;
            string parentFolder = string.Empty;
            string newFolder = string.Empty;

            server = "localhost";
            parentFolder = "\\";
            newFolder = "recursive{0}";
            deploy.DeleteFolder(server, "recursive0\\recursive1\\recursive2\\recursive3\\recursive4\\recursive5", "recursive6");
            deploy.DeleteFolder(server, "recursive0\\recursive1\\recursive2\\recursive3\\recursive4", "recursive5");
            deploy.DeleteFolder(server, "recursive0\\recursive1\\recursive2\\recursive3", "recursive4");
            deploy.DeleteFolder(server, "recursive0\\recursive1\\recursive2", "recursive3");
            deploy.DeleteFolder(server, "recursive0\\recursive1", "recursive2");
            deploy.DeleteFolder(server, "recursive0", "recursive1");
            deploy.DeleteFolder(server, "\\", "recursive0");
            System.Console.Read();
        }
    }
}
